const HISTORY_KEY = 'city_history'
const MAX_HISTORY = 8

// 获取历史记录
export const getHistoryCities = () => {
  try {
    return JSON.parse(uni.getStorageSync(HISTORY_KEY) || '[]')
  } catch (error) {
    console.error('获取历史记录失败:', error)
    return []
  }
}

// 保存到历史记录
export const saveToHistory = (city) => {
  try {
    let history = getHistoryCities()
    // 删除已存在的相同城市
    history = history.filter(item => item.id !== city.id)
    // 添加到开头
    history.unshift(city)
    // 限制数量
    if (history.length > MAX_HISTORY) {
      history = history.slice(0, MAX_HISTORY)
    }
    uni.setStorageSync(HISTORY_KEY, JSON.stringify(history))
  } catch (error) {
    console.error('保存历史记录失败:', error)
  }
}

// 清除历史记录
export const clearHistoryCities = () => {
  try {
    uni.removeStorageSync(HISTORY_KEY)
  } catch (error) {
    console.error('清除历史记录失败:', error)
  }
}